<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\LandingCompany;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function overview(Request $request): JsonResponse
    {
        $user = $request->user();

        if (!$user) {
            return response()->json([
                'code' => 401,
                'message' => '用户未认证',
                'data' => null,
            ], 401);
        }

        if (!$user->relationLoaded('tenant')) {
            $user->load('tenant');
        }

        $tenant = $user->tenant;

        if (!$tenant) {
            return response()->json([
                'code' => 404,
                'message' => '未找到租户信息',
                'data' => null,
            ], 404);
        }

        $landingCompanies = LandingCompany::query()
            ->where('status', LandingCompany::STATUS_ACTIVE)
            ->orderBy('name')
            ->get([
                'name',
                'tax_number',
                'bank_name',
                'account_number',
                'billing_categories',
            ])
            ->map(function (LandingCompany $company) {
                return [
                    'name' => $company->name,
                    'tax_number' => $company->tax_number,
                    'bank_name' => $company->bank_name,
                    'account_number' => $company->account_number,
                    'billing_categories' => $company->billing_categories ?: [],
                ];
            })
            ->values();

        return response()->json([
            'code' => 0,
            'message' => '获取首页概览成功',
            'data' => [
                'tenant' => [
                    'id' => $tenant->id,
                    'name' => $tenant->name,
                    'account_balance' => $tenant->account_balance,
                    'invoiceable_amount' => $tenant->invoiceable_amount,
                ],
                'landing_companies' => $landingCompanies,
            ],
        ]);
    }
}
